package com.fwj.authorization.staff.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fwj.authorization.staff.entity.SysDict;
import com.fwj.authorization.staff.entity.SysDictItem;
import com.fwj.authorization.staff.entity.vo.SysDictItemVO;
import com.fwj.authorization.staff.entity.vo.SysDictVO;
import com.fwj.authorization.staff.mapper.SysDictMapper;
import com.fwj.authorization.staff.service.SysDictItemService;
import com.fwj.authorization.staff.service.SysDictService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * SysDictServiceImpl
 *
 * @author 樊温军
 * @date 2025/3/22 上午11:28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    private final SysDictItemService sysDictItemService;

    @Override
    public IPage<SysDict> getPage(Page<SysDict> page, SysDict sysDict) {
        return baseMapper.getPage(page, sysDict);
    }

    @Override
    public List<SysDictItem> getItemList(SysDictItem sysDictItem) {
        return sysDictItemService.getItemList(sysDictItem);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveDict(SysDictVO sysDictVO) {
        SysDict sysDict = BeanUtil.copyProperties(sysDictVO, SysDict.class);
        List<SysDictItemVO> list = sysDictVO.getList();
        if (!CollectionUtils.isEmpty(list)) {
            int status = 0;
            List<SysDictItem> sysDictItems = BeanUtil.copyToList(list, SysDictItem.class);
            for (SysDictItem sysDictItem : sysDictItems) {
                sysDictItem.setDictCode(sysDict.getCode());
                if (sysDictItem.getStatus() == null) {
                    sysDictItem.setStatus(0);
                }
                status += sysDictItem.getStatus();
            }
            sysDictItemService.saveOrUpdateBatch(sysDictItems);
            sysDict.setStatus(status != 0 ? 1 : 0);
            this.saveOrUpdate(sysDict);
        }
        return sysDict.getId();
    }

    @Override
    public Boolean itemDel(List<Long> ids) {
        return sysDictItemService.removeByIds(ids);
    }

}
